package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import po.Order;
import po.Payment;
import po.Student;
import service.OrderService;
import service.PaymentService;
import utils.ResUtils;

import java.util.Date;
import java.util.List;
@Controller
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    // 获取支付列表数据 时间范围
    @PostMapping("/payments/list")
    @ResponseBody
    public Object AllPayment(@RequestBody Payment payment) {
        List<Payment> res = this.paymentService.allPayment(payment);
        if ( res != null) {
            return ResUtils.Success(1,"查询成功",res);
        } else {
            return ResUtils.Fail(0,"没有数据");
        }
    }



    // 获取为订单支付
    @PostMapping("/payments")
    public String addPayment(@RequestBody Payment payment, RedirectAttributes attr) {
//        System.out.println("接收到参数充值订单的" + payment.getOrderId());
//        System.out.println(payment);
        Date now = new Date();
        payment.setCreateTime(now);
        payment.setUpdateTime(now);
        Boolean res = this.paymentService.addPayment(payment);
        if (res) {
            attr.addAttribute("code",1);
            attr.addAttribute("orderId",payment.getOrderId());
            attr.addAttribute("money",payment.getMoney());
        } else {
            attr.addAttribute("code",0);
            attr.addAttribute("orderId",payment.getOrderId());
            attr.addAttribute("money",payment.getMoney());
        }
        // 转发到修改订单表的总金额
        System.out.println("转发到修改订单表的总金额");
        return "redirect:/orders/payment";
    }

    // 获取为新建订单时的支付
    @GetMapping("/payments/order")
    @ResponseBody
    public Object addPayment(@RequestParam("code") Integer code,
                                 @RequestParam("orderId") Integer orderId,
                                 @RequestParam("money") Double money) {

        Payment payment = new Payment();
        Date now = new Date();
        payment.setCreateTime(now);
        payment.setUpdateTime(now);
        payment.setOrderId(orderId);
        payment.setMoney(money);
        if (code == 1) {
            Boolean res = this.paymentService.addPayment(payment);
            if (res) {
                System.out.println("新增订单并充值成功");
                return ResUtils.Success(1, "新增订单并充值成功",payment);
            } else {
                return ResUtils.Fail(0, "新增订单失败");
            }
        }else {
            return ResUtils.Fail(0, "新增订单失败");
        }
    }
}
